package util.common;


import org.apache.commons.lang.RandomStringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码工具类
 */
public class VeriftyCodeUtil {
    /**
     *  图片验证码唯一标识
     */
    public static final String IDENTIFY_CODE_KEY = "_consts_identify_code_key_";

    /**
     * 获取验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public static void getRandomCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String random = RandomStringUtils.randomAlphanumeric(4);
        // 将四位数字的验证码保存到session中
        request.getSession().setAttribute(IDENTIFY_CODE_KEY,random);
        response.setContentType("image/jpeg");
        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        int width = 110, height = 33;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        //以下填充背景色
        g.setColor(new Color(225, 225, 225));
        Font DeFont = new Font("SansSerif", Font.PLAIN, 26);
        g.setFont(DeFont);
        g.fillRect(0, 0, width, height);
        //设置字体色
        g.setColor(Color.BLACK);
        g.drawString(random, 20, 25);
        g.dispose();
        try {
            ServletOutputStream outStream = response.getOutputStream();
            ImageIO.write(image, "JPG", outStream);
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片验证码
     */
    public static String getCmsCode(HttpServletRequest request) {
        if (request.getSession().getAttribute(IDENTIFY_CODE_KEY) != null) {
            return request.getSession().getAttribute(IDENTIFY_CODE_KEY).toString();
        } else {
            return null;
        }
    }
}


